<template>
    <div ref="playbackRef" class="absolute bottom-0 w-full bg-[var(--headBg)] duration-300" style="z-index:999">
        <!-- 进度条 -->
        <div class="slider-demo-block">
            <el-slider @change="sliderChange" @input="handleSliderInput" class="w-[calc(100%-24px)]" v-model="value"
                :step="0.01" :disabled="disabledValue" :max="audio.duration ? audio.duration : valueMax"
                :show-tooltip="false" />
        </div>
        <!-- 歌曲信息 -->
        <div class="flex justify-between px-5">
            <div class="flex items-center flex-1">
                <img id="imgRef" loading="eager" crossorigin="anonymous"
                    class="rounded-lg w-[70px] h-[70px] mb-1 hover:cursor-pointer"
                    @click="getLyricList(musicInfo as songInfo)" @load="imgLoad"
                    :src="musicInfo ? musicInfo.al.picUrl : 'https://s2.loli.net/2023/12/29/Y5RIrtXUBhAumq7.png'">
                <div class="ml-2">
                    <p :class="textColor ? 'text-[var(--iconBg)]' : 'text-[var(--icon)]'">{{
                        musicInfo?.name ? musicInfo.name : '暂无歌曲' }}
                        <span class="before:text-2xl iconfont icon-aixin text-[var(--playBg)] align-middle"></span>
                    </p>
                    <div class="flex w-96 overflow-hidden">
                        <p @click="goSingerDetail(item.id)" v-for="(item, index) in musicInfo?.ar"
                            :class="textColor ? 'text-[var(--iconBg)]' : 'text-[var(--icon)]'"
                            class="text-xs cursor-pointer hover:text-black whitespace-nowrap">{{
                                item.name
                            }}
                            <span>{{ index !== musicInfo!.ar.length - 1 ? ' / &nbsp;' : '' }}</span>
                        </p>
                    </div>

                </div>
            </div>
            <div class="flex flex-1 items-center translate-x-1/4">
                <!-- 播放模式 -->
                <i
                    class="before:text-2xl iconfont icon-suijisenlin before:text-[--playBg] hover:bg-[--active] cursor-pointer duration-300 rounded-full px-2 py-1"></i>
                <!-- 上一首 -->
                <i @click="previousSong"
                    class="before:text-2xl iconfont icon-diyiyeshouyeshangyishou mx-3 before:text-[--playBg] hover:bg-[--active] cursor-pointer duration-300 rounded-full px-2 py-1"></i>
                <!-- 暂停 -->
                <i @click="changeValue(2)" v-if="playback"
                    class="iconfont icon-zanting before:text-[3rem] text-[--playBg] hover:cursor-pointer "></i>
                <!-- 播放 -->
                <i @click="changeValue(1)" v-else
                    class="iconfont icon-bofang  hover:cursor-pointer before:text-[3rem] text-[--playBg]"></i>
                <!-- 下一首 -->
                <i @click="nextSong"
                    class="before:text-2xl iconfont icon-zuihouyiyemoyexiayishou mx-3 before:text-[--playBg] hover:bg-[--active] cursor-pointer duration-300 rounded-full px-2 py-1"></i>
                <!-- 桌面歌词 -->
                <span @click="openDesktopLyric"
                    class="text-xs text-[--playBg] before:text-[--playBg] hover:bg-[--active] cursor-pointer duration-300 rounded-full px-3.5 py-3">词</span>
            </div>
            <div class="flex flex-1 justify-end items-center">
                <!-- 歌曲当前时间 -->
                <span v-show="value < 60" :class="textColor ? 'text-[var(--iconBg)]' : 'text-[var(--icon)]'">00:
                </span>
                <span :class="textColor ? 'text-[var(--iconBg)]' : 'text-[var(--icon)]'">{{ value ?
                    songTime(value) : '00'
                    }}&nbsp;/&nbsp;</span>
                <!-- 歌曲总时间 -->
                <span :class="textColor ? 'text-[var(--iconBg)]' : 'text-[var(--icon)]'">{{ durTime }}</span>
                <span
                    class="text-[var(--playBg)] border border-[var(--playBg)] p-[2px] text-xs rounded-md ml-3">极高</span>
                <i
                    class="before:text-2xl iconfont icon-shengyin before:text-[--playBg] hover:bg-[--active] duration-300 rounded-full px-2 py-1 ml-3"></i>
                <i
                    class="before:text-2xl iconfont icon-shengyin1 before:text-[--playBg] hover:bg-[--active] duration-300 rounded-full px-2 py-1 ml-3"></i>
                <i
                    class="before:text-2xl iconfont icon-yonghuguanli_huaban before:text-[--playBg] hover:bg-[--active] duration-300 rounded-full px-2 py-1 ml-3"></i>
                <i @click="openNowPlayList"
                    class="before:text-xl iconfont icon-24gl-playlistMusic5 before:text-[--playBg] hover:bg-[--active] duration-300 rounded-full px-2.5 py-1.5 ml-3"></i>
            </div>
        </div>
        <!-- 播放器 -->
        <audio ref="audio" @timeupdate="changeTime" @ended="musicOver" @pause="audioPause"
            @playing="playing(musicInfo as songInfo)" :src="musicUrl.length > 0 ? musicUrl[0].url : ''">
        </audio>
        <!-- 播放列表区域 -->
        <el-drawer v-model="drawer" direction="rtl" :show-close="false" :with-header="false">
            <!-- 标头 -->
            <div class="h-20 border-b border-b-[var(--active)] pb-1 pt-3 pr-4 pl-6">
                <h1 class="text-xl text-[var(--text)] font-bold mb-2">当前播放</h1>
                <div class="flex justify-between ">
                    <div class="flex flex-1 items-center text-gray-600">
                        <span class="mr-1 text-xs">总{{ nowPlayList.length }}首</span>
                        <el-icon>
                            <Warning class="text-sm" />
                        </el-icon>
                    </div>
                    <div class="flex flex-1 justify-end">
                        <div class="hover:cursor-pointer text-[var(--text)]">
                            <i class="iconfont icon-shoucang"></i>
                            <span class="ml-1 text-sm">收藏全部</span>
                        </div>
                        <div class="flex items-center ml-3 hover:cursor-pointer text-[var(--playBg)]"
                            @click="clearList">
                            <el-icon>
                                <Delete />
                            </el-icon>
                            <span class="ml-1 text-sm">清空列表</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="h-[85.5%] overflow-auto customizedScrollbar relative">
                <!-- 播放列表 -->
                <ul v-if="nowPlayList.length > 0" class="b">
                    <li v-for="(item, index) in nowPlayList" ref="liStyle" @click="setListBg(index)"
                        @dblclick="start(item)"
                        class="flex select-none w-full justify-between items-center py-4 pr-5 my-1 text-[var(--text)] hover:text-current cursor-default hover:bg-[var(--active)] duration-300">
                        <div class="flex items-center w-44">
                            <div class="min-w-5 mr-1 text-end">
                                <i v-if="item.playing" class="iconfont icon-yinfu text-[var(--playBg)]"></i>
                            </div>
                            <p class="max-w-full mr-1 overflow-hidden whitespace-nowrap text-ellipsis">
                                {{ item.name }}</p>
                            <span v-if="!item.privilege?.pl"
                                class=" mr-1 min-w-fit border border-red-700 px-1 rounded-md text-xs text-red-700">vip</span>
                            <span v-if="item.sq !== null"
                                class=" mr-1 min-w-fit border border-[var(--playBg)] px-1 rounded-md text-xs text-[var(--playBg)] ">SQ</span>
                            <span @click="goMvPage(item.mv)" v-if="item.mv"
                                class=" mr-1 cursor-pointer min-w-fit border border-[var(--playBg)] px-1 rounded-md text-xs text-[var(--playBg)] ">MV</span>
                            <span v-if="item.privilege?.dlLevel !== 'none'"
                                class=" mr-1 min-w-fit border border-[var(--playBg)] px-1 rounded-md text-xs text-[var(--playBg)] ">Hi-Res</span>
                        </div>
                        <div class="w-32 flex">
                            <p v-for="(i, index) in item.ar" :key="i.id" @click="goToSingerDetail(i.id)"
                                class="max-w-full line-clamp-1 hover:text-gray-500 cursor-pointer">{{ i.name }}<span
                                    v-if="index !== item.ar.length - 1"> /&nbsp;</span></p>
                        </div>
                        <div class="w-fit">
                            <span>{{ setDuration((item.dt) as number) }}</span>
                        </div>
                    </li>
                </ul>
                <!-- 空状态 -->
                <el-empty v-else class="w-full absolute top-1/2 translate-y-[-60%]" :image-size="130"
                    description="您还没有添加任何歌曲！">
                    <span class="text-gray-500">去首页</span>
                    <span class="ml-1 text-sm border-b border-y-black hover:cursor-pointer" @click="goHome">发现音乐</span>
                </el-empty>
            </div>
        </el-drawer>
        <Teleport to="body">
            <!-- 桌面歌词 -->
            <desktopLyrics v-show="showDesktopLyric"></desktopLyrics>
        </Teleport>
    </div>
</template>

<script setup lang='ts'>
import { ref, onMounted, getCurrentInstance, computed, nextTick } from 'vue'
import { Delete, Warning } from "@element-plus/icons-vue"
import { songInfo } from '@renderer/store/modules/eveylSong/type'
import { songTime, setDuration } from '@renderer/hooks'
import { ElMessage } from 'element-plus'
import { useStore } from '@renderer/store'
import { storeToRefs } from 'pinia'
import { useRouter } from 'vue-router'
import ColorThief from 'colorthief';
const router = useRouter()
const { musicUrlInfo, lyric } = useStore()
const { musicUrl } = storeToRefs(musicUrlInfo)
const { lrc_lyricList } = storeToRefs(lyric)
const ctx = getCurrentInstance()
const bus = ctx?.appContext.config.globalProperties.$bus
const emit = defineEmits(['lrcInfo', 'getMusicInfo', 'getPlayTime', 'openDetails', 'ChangeRotatePause', 'ChangeRotateRun', 'stylusRotate', 'stylusRotatePause', 'colors'])
const playbackRef = ref<HTMLDivElement>()
const cacheMusicInfo = ref({} as musicInfoType)
// 音乐进度条
const value = ref(0)
const valueMax = ref(100)
const audio = ref({} as HTMLAudioElement)
const playback = ref(false)
const showDesktopLyric = ref(false)
const textColor = ref(true)
const disabledValue = ref(true)
const musicInfo = ref<songInfo>()
const songId = ref<number | string>(0)
const drawer = ref(false)
const userSlider = ref(false)
const liStyle = ref<HTMLUListElement[]>([])
const nowPlayList = ref<songInfo[]>(JSON.parse(localStorage.getItem('playList') as string) || [])
const colorThief = new ColorThief();
type musicInfoType = {
    musicUrl: string
    musicInfo: songInfo
    curTime: number
}
const durTime = computed(() => {
    if (musicInfo.value?.dt == undefined) return '00:00'
    else {
        return setDuration(musicInfo.value?.dt as number)
    }
})
onMounted(() => {
    bus.on('MusicInfo', (item: songInfo) => {
        start(item)
    })
    bus.on('closeDesktopLyric', () => {
        showDesktopLyric.value = false
    })
    bus.on('previousSong', () => {
        previousSong()
    })
    bus.on('nextSong', () => {
        nextSong()
    })
    bus.on('changeValue', (value: number) => {
        changeValue(value)
    })
    bus.on('openDesktopLyric', () => {
        getLyricList(musicInfo.value as songInfo)
    })
    bus.on('updatePlayList', () => {
        getNowPlayList()
    })
    bus.on('videoLoad', () => {
        changeValue(2)
    })
    // 获取缓存歌曲信息
    let isCacheMusic = JSON.parse(localStorage.getItem('cacheMusicInfo') as string)
    if (isCacheMusic) {
        cacheMusicInfo.value = isCacheMusic
        musicInfo.value = cacheMusicInfo.value.musicInfo
        audio.value.src = cacheMusicInfo.value.musicUrl
        audio.value.currentTime = cacheMusicInfo.value.curTime
        valueMax.value = cacheMusicInfo.value.musicInfo.dt as number / 1000
        playing(cacheMusicInfo.value.musicInfo)
    }
})
// 跳转歌手详情页
const goToSingerDetail = (id: number | string) => {
    router.push({ path: '/singerInfo', query: { id } })
    drawer.value = false
}
// 音乐时间改变
const changeTime = () => {
    if (!userSlider.value) {
        value.value = audio.value.currentTime
        emit('getPlayTime', audio.value.currentTime)
    }
    userSlider.value = false
}
// 监听用户拖动进度条
const handleSliderInput = (time: number) => {
    userSlider.value = true
    value.value = time
}
// 音乐进度条
const sliderChange = (time: number) => {
    userSlider.value = false
    audio.value.currentTime = time
    if (audio.value.paused) {
        audio.value.play()
        playback.value = true
    }
}
// 读取本地播放列表
const getNowPlayList = () => {
    nowPlayList.value = JSON.parse(localStorage.getItem('playList') as string) || []
}
const start = async (item: songInfo) => {
    getNowPlayList()
    musicInfo.value = item
    if (item.al.picUrl) {
        playMusic()
    }
}
// 暂停播放按钮改变音乐进度
const changeValue = (type: number) => {
    if (musicInfo.value === undefined) return
    if (type == 1) {
        audio.value.play()
        playback.value = true
        emit('ChangeRotateRun')
    } else {
        audio.value.pause()
        playback.value = false
        emit('ChangeRotatePause')
    }
}
// 播放
const playMusic = async () => {
    cacheMusicInfo.value.musicInfo = musicInfo.value as songInfo
    if (!(musicInfo.value?.privilege?.freeTrialPrivilege.cannotListenReason == 0 || !musicInfo.value?.privilege?.pl)) {
        let src = "http://music.163.com/song/media/outer/url?id=" + musicInfo.value?.id + ".mp3"
        audio.value.src = src
        cacheMusicInfo.value.musicUrl = src
    } else {
        let res = await musicUrlInfo.setMusicUrl(musicInfo.value?.id as number)
        if (!res) {
            ElMessage.warning('该歌曲无版权,将为您切换下一首')
            audio.value.pause()
            emit('ChangeRotatePause')
            playback.value = false
            audio.value.load()
            setTimeout(() => {
                nextSong()
            }, 2000);
            return
        } else {
            cacheMusicInfo.value.musicUrl = musicUrl.value[0].url
        }
    }
    audio.value.load()
    emit('ChangeRotateRun')
    audio.value.play()
    playback.value = true
    setPlayingStyle()
}
// 音乐暂停
const audioPause = () => {
    bus.emit('audioStatus', false)
}
// 音乐播放结束
function musicOver() {
    value.value = 0
    let MusicIndex = nowPlayList.value.findIndex((item: songInfo) => {
        return item.id == musicInfo.value?.id
    })
    if (MusicIndex == nowPlayList.value.length - 1) {
        playback.value = false
        emit('ChangeRotatePause')
    } else {
        start(nowPlayList.value[MusicIndex + 1])
    }
}
// 恢复播放器背景
function resetPlayback() {
    setTimeout(() => {
        playbackRef.value!.style.backgroundColor = 'var(--headBg)'
        textColor.value = true
    }, 300);

}
defineExpose({
    resetPlayback
})
// 开始播放的回调
const playing = async (item: songInfo) => {
    disabledValue.value = false
    if (songId.value !== item.id) {
        lrc_lyricList.value = []
        await lyric.getLyricList(item.id as number)
        songId.value = item.id
        emit('lrcInfo', { lrc_lyricList: lrc_lyricList.value, item })
    }
    emit('getMusicInfo', cacheMusicInfo.value)
    sessionStorage.setItem('playMusicId', JSON.stringify(item.id))
    if (!audio.value.paused) {
        // 告知桌面歌词当前音乐播放状态
        bus.emit('audioStatus', true)
    }
}
// 点击展开歌词详情页
const getLyricList = async (item: songInfo) => {
    if (item == undefined) {
        ElMessage.warning('请先选择歌曲')
        return
    }
    if (textColor.value) {
        if (audio.value.paused) {
            emit('ChangeRotatePause')
        }
        setTimeout(() => {
            playbackRef.value!.style.backgroundColor = 'rgba(0, 0, 0, 0.1)'
            textColor.value = false
        }, 80)
        emit('openDetails')
    }
}
// 图片加载完成事件
const imgLoad = () => {
    const img = document.getElementById('imgRef') as HTMLImageElement
    getImgColor(img)
}
// 获取图片主色
const getImgColor = async (img: HTMLImageElement) => {
    let colors: Array<string> = []
    colors = await colorThief.getPalette(img, 5);
    colors ? colors = colors.map(c => { return `rgb(${c[0]}, ${c[1]}, ${c[2]})` }) : colors = []
    document.documentElement.style.setProperty('--c1', colors.length ? colors[0] : "#ff9a9e")
    document.documentElement.style.setProperty('--c2', colors.length ? colors[1] : "#fad0c4")
    document.documentElement.style.setProperty('--c3', colors.length ? colors[2] : "#fad0c4")
    document.documentElement.style.setProperty('--c4', colors.length ? colors[3] : "#ff9a9e")
    document.documentElement.style.setProperty('--c5', colors.length ? colors[4] : "#fad0c4")
}
// 排他改变li样式
const setListBg = (index: number) => {
    liStyle.value.forEach((item, i) => {
        item.style.backgroundColor = ''
        if (index == i) {
            liStyle.value[i].style.backgroundColor = 'var(--active)'
        }
    })
}
// 返回首页
const goHome = () => {
    router.push('/')
    drawer.value = false
}
// 跳转mv详情页
const goMvPage = (id: number) => {
    router.push({ name: 'mv', query: { id } })
    drawer.value = false
}
// 跳转歌手详情页
const goSingerDetail = (id: number | string) => {
    router.push({ path: '/singerInfo', query: { id } })
}
// 清空列表
const clearList = () => {
    nowPlayList.value = []
    localStorage.setItem('playList', JSON.stringify([]));
}
// 当前播放列表
const openNowPlayList = () => {
    drawer.value = true
    setPlayingStyle()
}
// 播放列表设置当前播放的歌曲样式
const setPlayingStyle = () => {
    nowPlayList.value.forEach((item, index) => {
        if (musicInfo.value?.id == item.id) {
            nextTick(() => {
                liStyle.value.forEach((item, i) => {
                    item.style.backgroundColor = ''
                    liStyle.value[i].style.color = ''
                    if (index == i) {
                        liStyle.value[i].style.backgroundColor = 'var(--active)'
                        liStyle.value[i].style.color = 'var(--playBg)'
                    }
                })
            })
            item.playing = false
            nowPlayList.value[index].playing = true
        }
    })
}
// 上一首
const previousSong = () => {
    if (audio.value.src !== "http://localhost:5173/") {
        let MusicIndex = nowPlayList.value.findIndex((item: songInfo) => {
            return item.id == musicInfo.value?.id
        })
        // 判断当前播放歌曲是否是第一首
        if (MusicIndex == 0) {
            start(musicInfo.value as songInfo)
        } else {
            start(nowPlayList.value[MusicIndex - 1])
        }
    }

}
// 下一首
const nextSong = () => {
    if (audio.value.src !== "http://localhost:5173/") {
        let MusicIndex = nowPlayList.value.findIndex((item: songInfo) => {
            return item.id == musicInfo.value?.id
        })
        // 判断当前播放歌曲是否是最后一首
        if (MusicIndex == nowPlayList.value.length - 1) {
            start(nowPlayList.value[0])
        } else {
            start(nowPlayList.value[MusicIndex + 1])
        }
    }
}
// 开启桌面歌词
const openDesktopLyric = () => {
    showDesktopLyric.value = !showDesktopLyric.value
}
</script>
<style scoped lang='less'>
:deep(.el-slider) {
    overflow: hidden;
}

:deep(.el-slider__runway) {
    background-color: var(--inputBg);
}

:deep(.el-slider__bar) {
    background: var(--playBg)
}

:deep(.el-slider__button) {
    border-color: var(--playBg);
}

:deep(.el-drawer.rtl) {
    background-color: var(--inputBg);
    backdrop-filter: blur(10px);
    height: 80%;
    top: 10%;
    border-top-left-radius: 8px;
    border-bottom-left-radius: 8px;
}

:deep(.el-drawer__body) {
    padding: 0
}

:deep(.el-overlay) {
    background-color: transparent;
}
</style>